package com.zyw.mvc.servlet;

import com.zyw.mvc.support.WrappedResult;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhangyw
 * @date 2017/2/9 15:06
 */
@Controller
@RequestMapping("/error")
public class ErrorPageController extends BaseController {

    @RequestMapping("400")
    @ResponseBody
    public WrappedResult _400(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return WrappedResult.handleExceptionWrappedResult(400, "Bad request", null);
    }

    @RequestMapping("401")
    @ResponseBody
    public WrappedResult _401(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return WrappedResult.handleExceptionWrappedResult(401, "未认证", null);
    }

    @RequestMapping("403")
    @ResponseBody
    public WrappedResult _403(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return WrappedResult.handleExceptionWrappedResult(403, "禁止访问", null);
    }

    @RequestMapping("404")
    @ResponseBody
    public WrappedResult _404(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ServletRequest servletRequest = new DefaultMultipartHttpServletRequest(request).getRequest();
        String errorMsg = String.valueOf(servletRequest.getAttribute("javax.servlet.error.request_uri"));
        return WrappedResult.handleExceptionWrappedResult(404, "未找到服务", errorMsg);
    }

    @RequestMapping("405")
    @ResponseBody
    public WrappedResult _405(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return WrappedResult.handleExceptionWrappedResult(405, "不允许的请求方式", (String) request.getAttribute("javax.servlet.error.message"));
    }

    @RequestMapping("500")
    @ResponseBody
    public WrappedResult _500(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ServletRequest servletRequest = new DefaultMultipartHttpServletRequest(request).getRequest();
        Exception exception = ((Exception) servletRequest.getAttribute("javax.servlet.error.exception"));
        String errorMsg = ExceptionUtils.getStackTrace(exception);
        return WrappedResult.handleExceptionWrappedResult(500, "服务异常", errorMsg);
    }

}
